/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.jjsoft.disco.gco.view;

import com.jjsoft.disco.gco.mdl.Detallefactura;
import com.jjsoft.disco.gco.mdl.Factura;
import com.jjsoft.disco.gco.mdl.Usuario;
import com.jjsoft.disco.gco.ngc.FacturaManager;
import com.jjsoft.disco.gco.ngc.ProductoManager;
import com.jjsoft.disco.gco.ngc.UsuarioManager;
import com.jjsoft.disco.gco.util.CNumeros;
import com.jjsoft.disco.gco.util.CSelecciones;
import com.jjsoft.disco.gco.util.MiModelo;
import com.jjsoft.disco.gco.util.configuraciones;
import java.awt.event.KeyEvent;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JButton;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import javax.swing.UIManager;

/**
 *
 * @author johnny
 */
public class VFactura extends javax.swing.JFrame {

    /**
     * Creates new form VFactura
     */
    Factura factura;
    JTextField texto;
    MiModelo modelo = new MiModelo();
    List<Detallefactura> listaDetalle = new ArrayList<Detallefactura>();
    List<Detallefactura> vendidosRecientes = new ArrayList<Detallefactura>();
    JButton boton;
    boolean descuento;

    public VFactura(Factura fact, JButton boton) {
        //setIconImage(new ImageIcon(getClass().getResource("/img/1362798841_CellPhone.png")).getImage());
        initComponents();
        this.factura = fact;
        this.boton = boton;
        descuento = false;
        cmdAgregar.setMnemonic(KeyEvent.VK_A);
        cmdGuardar.setMnemonic(KeyEvent.VK_G);
        cmdQuitar.setMnemonic(KeyEvent.VK_Q);
        this.texto = texto;
        this.txtCedula.setText(factura.getCedulaCliente().getCedula());
        this.txtCliente.setText(factura.getCedulaCliente().getNombres() + " " + factura.getCedulaCliente().getApellidos());
        this.txtTelefono.setText(factura.getCedulaCliente().getTelefono());
        this.txtDireccion.setText(factura.getCedulaCliente().getDireccion());
        this.txtFecha.setText(factura.getFecha().toLocaleString());
        this.txtNumero.setText(factura.getNumero().toString());
        this.txtPrecio.setEditable(false);
        this.txtDescuento.setEnabled(false);
        String[] identificadores = {"CANT", "DESCRIPCION", "BARRA", "P. UNIT", "V. VENTA"};
        this.modelo.setColumnIdentifiers(identificadores);
        this.dtgFactura.setModel(this.modelo);
        this.dtgFactura.getColumn("CANT").setPreferredWidth(30);
        this.dtgFactura.getColumn("DESCRIPCION").setPreferredWidth(330);
        this.dtgFactura.getColumn("P. UNIT").setPreferredWidth(50);
        this.dtgFactura.getColumn("V. VENTA").setPreferredWidth(50);
        if (factura.getDetallefacturaList() != null && factura.getDetallefacturaList().size() > 0) {
            this.listaDetalle = factura.getDetallefacturaList();
            for (int i = listaDetalle.size() - 1; i >= 0; i--) {
                if (listaDetalle.get(i).getBarra() != configuraciones.barra) {
                    listaDetalle.remove(i);
                }
            }
            cargaDatos();
        }
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        txtCliente = new javax.swing.JTextField();
        jLabel4 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        txtTelefono = new javax.swing.JTextField();
        txtCedula = new javax.swing.JTextField();
        jLabel6 = new javax.swing.JLabel();
        txtFecha = new javax.swing.JTextField();
        jLabel7 = new javax.swing.JLabel();
        txtNumero = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        txtDireccion = new javax.swing.JTextField();
        jSeparator1 = new javax.swing.JSeparator();
        jScrollPane1 = new javax.swing.JScrollPane();
        dtgFactura = new javax.swing.JTable();
        txtCodigo = new javax.swing.JTextField();
        jLabel9 = new javax.swing.JLabel();
        jButton1 = new javax.swing.JButton();
        jLabel10 = new javax.swing.JLabel();
        jLabel11 = new javax.swing.JLabel();
        txtPrecio = new javax.swing.JTextField();
        cmdAgregar = new javax.swing.JButton();
        jLabel12 = new javax.swing.JLabel();
        txtSubtotal = new javax.swing.JTextField();
        jLabel13 = new javax.swing.JLabel();
        jLabel14 = new javax.swing.JLabel();
        txtSubtotalD = new javax.swing.JTextField();
        jLabel15 = new javax.swing.JLabel();
        txtIVA = new javax.swing.JTextField();
        cmdQuitar = new javax.swing.JButton();
        cmdGuardar = new javax.swing.JButton();
        txtDescuento = new javax.swing.JSpinner();
        jLabel16 = new javax.swing.JLabel();
        txtTotal = new javax.swing.JTextField();
        txtCantidad = new javax.swing.JSpinner();
        jLabel17 = new javax.swing.JLabel();
        cmdDescuento = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosed(java.awt.event.WindowEvent evt) {
                formWindowClosed(evt);
            }
        });
        addComponentListener(new java.awt.event.ComponentAdapter() {
            public void componentHidden(java.awt.event.ComponentEvent evt) {
                formComponentHidden(evt);
            }
        });

        jLabel1.setFont(new java.awt.Font("Ubuntu", 1, 18)); // NOI18N
        jLabel1.setText("FACTURA");

        jLabel3.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        jLabel3.setForeground(new java.awt.Color(51, 51, 51));
        jLabel3.setText("Cliente:");

        txtCliente.setEditable(false);
        txtCliente.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                txtClienteActionPerformed(evt);
            }
        });

        jLabel4.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        jLabel4.setForeground(new java.awt.Color(51, 51, 51));
        jLabel4.setText("RUC / C.I:");

        jLabel5.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        jLabel5.setForeground(new java.awt.Color(51, 51, 51));
        jLabel5.setText("Telf:");

        txtTelefono.setEditable(false);

        txtCedula.setEditable(false);
        txtCedula.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                txtCedulaActionPerformed(evt);
            }
        });

        jLabel6.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        jLabel6.setForeground(new java.awt.Color(51, 51, 51));
        jLabel6.setText("Fecha de Emision:");

        txtFecha.setEditable(false);

        jLabel7.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        jLabel7.setForeground(new java.awt.Color(51, 51, 51));
        jLabel7.setText("Numero:");

        txtNumero.setEditable(false);
        txtNumero.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                txtNumeroActionPerformed(evt);
            }
        });
        txtNumero.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                txtNumeroKeyReleased(evt);
            }
        });

        jLabel2.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        jLabel2.setForeground(new java.awt.Color(51, 51, 51));
        jLabel2.setText("Direccion:");

        txtDireccion.setEditable(false);

        dtgFactura.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
        jScrollPane1.setViewportView(dtgFactura);

        txtCodigo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                txtCodigoActionPerformed(evt);
            }
        });
        txtCodigo.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                txtCodigoKeyReleased(evt);
            }
            public void keyPressed(java.awt.event.KeyEvent evt) {
                txtCodigoKeyPressed(evt);
            }
        });

        jLabel9.setText("Codigo:");

        jButton1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/search-database.png"))); // NOI18N
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jLabel10.setText("Cantidad:");

        jLabel11.setText("P. Unit");

        txtPrecio.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                txtPrecioKeyReleased(evt);
            }
        });

        cmdAgregar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/add.png"))); // NOI18N
        cmdAgregar.setText("Agregar");
        cmdAgregar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cmdAgregarActionPerformed(evt);
            }
        });

        jLabel12.setText("Subtotal_0:");

        txtSubtotal.setEnabled(false);

        jLabel13.setText("Descuento:");

        jLabel14.setText("Subtotal_D:");

        txtSubtotalD.setEnabled(false);

        jLabel15.setText("IVA:");

        txtIVA.setEnabled(false);

        cmdQuitar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/delete.png"))); // NOI18N
        cmdQuitar.setText("    Quitar");
        cmdQuitar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cmdQuitarActionPerformed(evt);
            }
        });

        cmdGuardar.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
        cmdGuardar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/save.png"))); // NOI18N
        cmdGuardar.setText("     GUARDAR");
        cmdGuardar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cmdGuardarActionPerformed(evt);
            }
        });

        txtDescuento.setModel(new javax.swing.SpinnerNumberModel(0, 0, 100, 1));
        txtDescuento.addChangeListener(new javax.swing.event.ChangeListener() {
            public void stateChanged(javax.swing.event.ChangeEvent evt) {
                txtDescuentoStateChanged(evt);
            }
        });

        jLabel16.setText("Total:");

        txtTotal.setEditable(false);
        txtTotal.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N
        txtTotal.setForeground(new java.awt.Color(255, 0, 0));

        txtCantidad.setModel(new javax.swing.SpinnerNumberModel(Integer.valueOf(1), Integer.valueOf(1), null, Integer.valueOf(1)));

        jLabel17.setText("%");

        cmdDescuento.setText("Aplicar Descuento");
        cmdDescuento.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cmdDescuentoActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 572, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jLabel9)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(txtCodigo, javax.swing.GroupLayout.PREFERRED_SIZE, 89, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(390, 390, 390))))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(32, 32, 32)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addGap(205, 205, 205)
                                .addComponent(jLabel10)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(txtCantidad, javax.swing.GroupLayout.PREFERRED_SIZE, 59, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jLabel11)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(txtPrecio, javax.swing.GroupLayout.PREFERRED_SIZE, 89, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(cmdAgregar, javax.swing.GroupLayout.PREFERRED_SIZE, 95, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(0, 1, Short.MAX_VALUE))
                            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addGroup(layout.createSequentialGroup()
                                        .addComponent(cmdQuitar)
                                        .addGap(18, 18, 18)
                                        .addComponent(cmdDescuento))
                                    .addComponent(cmdGuardar))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(jLabel13, javax.swing.GroupLayout.Alignment.TRAILING)
                                    .addComponent(jLabel12, javax.swing.GroupLayout.Alignment.TRAILING)
                                    .addComponent(jLabel16, javax.swing.GroupLayout.Alignment.TRAILING)
                                    .addComponent(jLabel14, javax.swing.GroupLayout.Alignment.TRAILING)
                                    .addComponent(jLabel15, javax.swing.GroupLayout.Alignment.TRAILING))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                        .addComponent(txtDescuento, javax.swing.GroupLayout.DEFAULT_SIZE, 87, Short.MAX_VALUE)
                                        .addComponent(txtSubtotal)
                                        .addComponent(txtSubtotalD, javax.swing.GroupLayout.Alignment.TRAILING)
                                        .addComponent(txtIVA, javax.swing.GroupLayout.Alignment.TRAILING))
                                    .addComponent(txtTotal, javax.swing.GroupLayout.PREFERRED_SIZE, 87, javax.swing.GroupLayout.PREFERRED_SIZE)))
                            .addGroup(layout.createSequentialGroup()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                                    .addComponent(jLabel4)
                                    .addComponent(jLabel3)
                                    .addComponent(jLabel7)
                                    .addComponent(jLabel2))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(txtNumero, javax.swing.GroupLayout.PREFERRED_SIZE, 120, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addGroup(layout.createSequentialGroup()
                                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                                            .addComponent(jLabel1)
                                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                                                .addComponent(txtDireccion, javax.swing.GroupLayout.Alignment.LEADING)
                                                .addComponent(txtCedula, javax.swing.GroupLayout.Alignment.LEADING)
                                                .addComponent(txtCliente, javax.swing.GroupLayout.PREFERRED_SIZE, 235, javax.swing.GroupLayout.PREFERRED_SIZE)))
                                        .addGap(18, 18, 18)
                                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                                            .addComponent(jLabel6)
                                            .addComponent(jLabel5))
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                                            .addComponent(txtFecha, javax.swing.GroupLayout.Alignment.LEADING)
                                            .addComponent(txtTelefono, javax.swing.GroupLayout.Alignment.LEADING)))))
                            .addComponent(jSeparator1))))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabel17)
                .addGap(29, 29, 29))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1)
                .addGap(38, 38, 38)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel7)
                    .addComponent(txtNumero, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(txtCliente, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel5)
                    .addComponent(txtTelefono, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel4)
                    .addComponent(txtCedula, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel6)
                    .addComponent(txtFecha, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(txtDireccion, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel2))
                .addGap(18, 18, 18)
                .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jButton1, javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(txtCodigo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(jLabel9)
                        .addComponent(jLabel10)
                        .addComponent(jLabel11)
                        .addComponent(txtPrecio, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(cmdAgregar)
                        .addComponent(txtCantidad, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(10, 10, 10)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel12)
                    .addComponent(txtSubtotal, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(cmdQuitar)
                    .addComponent(cmdDescuento, javax.swing.GroupLayout.PREFERRED_SIZE, 29, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel13)
                    .addComponent(txtDescuento, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel17))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(txtSubtotalD, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel14))
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel15)
                            .addComponent(txtIVA, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(txtTotal, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel16)))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(24, 24, 24)
                        .addComponent(cmdGuardar)))
                .addContainerGap(17, Short.MAX_VALUE))
        );

        setSize(new java.awt.Dimension(614, 671));
        setLocationRelativeTo(null);
    }// </editor-fold>//GEN-END:initComponents

    private void txtCedulaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtCedulaActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_txtCedulaActionPerformed

    private void txtClienteActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtClienteActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_txtClienteActionPerformed

    private void txtCodigoKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtCodigoKeyPressed
        // TODO add your handling code here:
        if (evt.getKeyCode() == 10) {
            CSelecciones.producto = new ProductoManager().buscarPorCodigo(txtCodigo.getText());
            if (CSelecciones.producto != null) {
                txtPrecio.setText(CSelecciones.producto.getPrecioVenta().toString());
            } else {
                JOptionPane.showMessageDialog(rootPane, "No se ha encontrado un producto con ese codigo", "Error", JOptionPane.ERROR_MESSAGE);
            }
        }
    }//GEN-LAST:event_txtCodigoKeyPressed

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        // TODO add your handling code here:

        CSelecciones.texto1 = txtCodigo;
        CSelecciones.texto2 = txtPrecio;
        new VSeleccionArticulo(true).setVisible(true);
    }//GEN-LAST:event_jButton1ActionPerformed

    private void cmdAgregarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cmdAgregarActionPerformed
        // TODO add your handling code here:
        if (CSelecciones.producto != null) {
            double precio = 0;
            int cantidad = Integer.parseInt(txtCantidad.getValue().toString());
            try {
                precio = Double.parseDouble(txtPrecio.getText()) / (configuraciones.iva / 100D + 1);
            } catch (Exception ex) {
                JOptionPane.showMessageDialog(rootPane, "Campo precio incorrecto", "Error", JOptionPane.ERROR_MESSAGE);
                return;
            }
            boolean existe = false;
            for (int i = 0; i < listaDetalle.size(); i++) {
                if (listaDetalle.get(i).getIdArticulo().equals(CSelecciones.producto) && listaDetalle.get(i).getBarra() == configuraciones.barra && listaDetalle.get(i).getPrecioVenta() == precio) {

                    existe = true;
                    int nuevaCantidad = 0;
                    nuevaCantidad = listaDetalle.get(i).getCantidad() + cantidad;
                    if (cantidad <= CSelecciones.producto.getStock()) {
                        listaDetalle.get(i).setCantidad(nuevaCantidad);
                        dtgFactura.setValueAt(String.valueOf(nuevaCantidad), i, 0);
                        dtgFactura.setValueAt(String.valueOf(CNumeros.redondear((double) nuevaCantidad * precio)), i, 3);
                        Detallefactura vendido = new Detallefactura();
                        agregarVendido(cantidad, precio);
                        Calcular();
                        CSelecciones.producto = null;
                        txtCantidad.setValue(1);
                        txtPrecio.setText("");
                        txtCodigo.setText("");
                    } else {
                        JOptionPane.showMessageDialog(rootPane, "No existen suficientes productos en stock", "Error", JOptionPane.ERROR_MESSAGE);
                        return;
                    }

                }
            }
            if (!existe) {
                if (cantidad <= CSelecciones.producto.getStock()) {
                    agregarProducto(cantidad, precio);
                } else {
                    JOptionPane.showMessageDialog(rootPane, "No existen suficientes productos en stock", "Error", JOptionPane.ERROR_MESSAGE);
                    return;
                }
            }


        } else {
            JOptionPane.showMessageDialog(rootPane, "No ha seleccionado un producto", "Error", JOptionPane.ERROR_MESSAGE);
            return;
        }
    }//GEN-LAST:event_cmdAgregarActionPerformed

    private void txtDescuentoStateChanged(javax.swing.event.ChangeEvent evt) {//GEN-FIRST:event_txtDescuentoStateChanged
        // TODO add your handling code here:
        Calcular();
    }//GEN-LAST:event_txtDescuentoStateChanged

    private void cmdQuitarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cmdQuitarActionPerformed
        // TODO add your handling code here:

        if (dtgFactura.getSelectedRow() != -1) {
            if (JOptionPane.showConfirmDialog(rootPane, "Esta seguro?", "Quitar Producto", JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION) {
                int i = dtgFactura.getSelectedRow();
                if (listaDetalle.get(i).getIddetalleFactura() != null) {
                    String tarjeta = JOptionPane.showInputDialog("Deslice una tarjeta de administrador");
                    UsuarioManager us = new UsuarioManager();
                    Usuario usuario = us.buscarPorPassword(tarjeta);
                    if (usuario != null && usuario.getRol() == 0) {
                        modelo.removeRow(i);
                        listaDetalle.remove(i);
                        Calcular();
                    } else {
                        JOptionPane.showMessageDialog(rootPane, "Tarjeta Invalida");
                        return;
                    }
                } else {
                    modelo.removeRow(i);
                    listaDetalle.remove(i);
                    Calcular();
                }

            }
        } else {
            JOptionPane.showMessageDialog(rootPane, "Primero Seleccione un producto", "Error", JOptionPane.ERROR_MESSAGE);
        }
    }//GEN-LAST:event_cmdQuitarActionPerformed

    private void cmdGuardarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cmdGuardarActionPerformed
        // TODO add your handling code here:
        if (this.listaDetalle.size() > 0) {
            if (JOptionPane.showConfirmDialog(this.rootPane, "Está seguro de guardar la factura", "Guardar Factura", 1) == 0) {
                factura.setDescuento(Double.valueOf(Double.parseDouble(String.valueOf(this.txtDescuento.getValue()))));
                factura.setIva(Double.valueOf(Double.parseDouble(this.txtIVA.getText())));
                factura.setSubtotal(Double.valueOf(Double.parseDouble(this.txtSubtotal.getText())));
                factura.setTotal(Double.valueOf(Double.parseDouble(this.txtTotal.getText())));
                new FacturaManager().editarFactura(factura, listaDetalle, vendidosRecientes);
                JOptionPane.showMessageDialog(rootPane, "Venta Guardada");
                this.dispose();
            }
        } else {
            JOptionPane.showMessageDialog(this.rootPane, "No se han agregado articulos a la factura", "Error", 0);
        }

    }//GEN-LAST:event_cmdGuardarActionPerformed

    private void txtNumeroKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtNumeroKeyReleased
        // TODO add your handling code here:
        /*Validacion validar = new Validacion();
         validar.numeros(evt, txtNumero);*/
    }//GEN-LAST:event_txtNumeroKeyReleased

    private void txtCodigoKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtCodigoKeyReleased
        // TODO add your handling code here:
    }//GEN-LAST:event_txtCodigoKeyReleased

    private void txtPrecioKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtPrecioKeyReleased
        // TODO add your handling code here:
        /*
         Validacion validar = new Validacion();
         validar.decimal(evt, txtPrecio);*/
    }//GEN-LAST:event_txtPrecioKeyReleased

    private void txtNumeroActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtNumeroActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_txtNumeroActionPerformed

    private void txtCodigoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtCodigoActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_txtCodigoActionPerformed

    private void formComponentHidden(java.awt.event.ComponentEvent evt) {//GEN-FIRST:event_formComponentHidden
        // TODO add your handling code here:
    }//GEN-LAST:event_formComponentHidden

    private void formWindowClosed(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosed
        //JOptionPane.showMessageDialog(rootPane, "Cerrando");
        boton.doClick();
    }//GEN-LAST:event_formWindowClosed

    private void cmdDescuentoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cmdDescuentoActionPerformed
        // TODO add your handling code here:
        if (!descuento) {
            String tarjeta = JOptionPane.showInputDialog("Ingrese una tarjeta de administrador");
            if (tarjeta != null && !tarjeta.equals("")) {
                Usuario usuario = new UsuarioManager().buscarPorPassword(tarjeta);
                if (usuario != null) {
                    txtPrecio.setEditable(true);
                    txtDescuento.setEnabled(true);
                    cmdDescuento.setText("Aceptar");
                    descuento = true;
                } else {
                    JOptionPane.showMessageDialog(rootPane, "Tarjeta Incorrecta");
                }
            }
        }
        else
        {
            cmdDescuento.setText("Aplicar Descuento");
            txtDescuento.setEnabled(false);
            txtPrecio.setEditable(false);
        }
    }//GEN-LAST:event_cmdDescuentoActionPerformed

    /**
     * @param args the command line arguments
     */
    private void Calcular() {

        double subtotal = 0.0D;
        double iva = 0.0D;
        double desc = Double.parseDouble(String.valueOf(this.txtDescuento.getValue()));
        for (int i = 0; i < this.listaDetalle.size(); i++) {
            subtotal += CNumeros.redondear(((Detallefactura) this.listaDetalle.get(i)).getCantidad().doubleValue() * ((Detallefactura) this.listaDetalle.get(i)).getPrecioVenta().doubleValue());

            double sd = CNumeros.redondear(((Detallefactura) this.listaDetalle.get(i)).getCantidad().doubleValue() * ((Detallefactura) this.listaDetalle.get(i)).getPrecioVenta().doubleValue());
            sd = CNumeros.redondear(sd - sd * desc / 100.0D);
            iva += CNumeros.redondear(sd * configuraciones.iva / 100.0D);
        }

        double subtd = CNumeros.redondear(subtotal - subtotal * desc / 100.0D);
        double total = CNumeros.redondear(subtd + iva);
        this.txtSubtotal.setText(String.valueOf(CNumeros.redondear(subtotal)));
        this.txtSubtotalD.setText(String.valueOf(CNumeros.redondear(subtd)));
        this.txtIVA.setText(String.valueOf(CNumeros.redondear(iva)));
        this.txtTotal.setText(String.valueOf(CNumeros.redondear(total)));
    }

    public void agregarProducto(int cantidad, double precio) {
        Detallefactura detalle = new Detallefactura();
        detalle.setCantidad(cantidad);
        detalle.setPrecioVenta(precio);
        detalle.setNumero(factura);
        detalle.setIdArticulo(CSelecciones.producto);
        detalle.setBarra(configuraciones.barra);
        listaDetalle.add(detalle);
        vendidosRecientes.add(detalle);
        String[] Articulo = {String.valueOf(cantidad), CSelecciones.producto.getDescripcion(), String.valueOf(configuraciones.barra), CNumeros.redondear(precio) + "", String.valueOf(CNumeros.redondear(precio * cantidad))};
        modelo.addRow(Articulo);
        CSelecciones.producto = null;
        txtCantidad.setValue(1);
        txtPrecio.setText("");
        txtCodigo.setText("");
        Calcular();

    }

    private void agregarVendido(int cantidad, double precio) {
        Detallefactura detalle = new Detallefactura();
        detalle.setCantidad(cantidad);
        detalle.setPrecioVenta(precio);
        detalle.setNumero(factura);
        detalle.setIdArticulo(CSelecciones.producto);
        detalle.setBarra(configuraciones.barra);
        vendidosRecientes.add(detalle);
    }

    public void cargaDatos() {
        for (int i = 0; i < listaDetalle.size(); i++) {
            String[] Articulo = {String.valueOf(listaDetalle.get(i).getCantidad()), listaDetalle.get(i).getIdArticulo().getDescripcion(), listaDetalle.get(i).getBarra().toString(), CNumeros.redondear(listaDetalle.get(i).getPrecioVenta()) + "", String.valueOf(CNumeros.redondear(listaDetalle.get(i).getPrecioVenta() * listaDetalle.get(i).getCantidad()))};
            modelo.addRow(Articulo);
        }
        CSelecciones.producto = null;
        txtDescuento.setValue(factura.getDescuento());
        Calcular();
    }

    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(VFactura.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(VFactura.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(VFactura.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(VFactura.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>
        try {
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        } catch (Exception e) {
            System.out.println("Error setting native LAF: " + e);
        }
        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new VFactura(new Factura(), null).setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton cmdAgregar;
    private javax.swing.JButton cmdDescuento;
    private javax.swing.JButton cmdGuardar;
    private javax.swing.JButton cmdQuitar;
    private javax.swing.JTable dtgFactura;
    private javax.swing.JButton jButton1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel10;
    private javax.swing.JLabel jLabel11;
    private javax.swing.JLabel jLabel12;
    private javax.swing.JLabel jLabel13;
    private javax.swing.JLabel jLabel14;
    private javax.swing.JLabel jLabel15;
    private javax.swing.JLabel jLabel16;
    private javax.swing.JLabel jLabel17;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLabel jLabel9;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JSeparator jSeparator1;
    private javax.swing.JSpinner txtCantidad;
    private javax.swing.JTextField txtCedula;
    private javax.swing.JTextField txtCliente;
    private javax.swing.JTextField txtCodigo;
    private javax.swing.JSpinner txtDescuento;
    private javax.swing.JTextField txtDireccion;
    private javax.swing.JTextField txtFecha;
    private javax.swing.JTextField txtIVA;
    private javax.swing.JTextField txtNumero;
    private javax.swing.JTextField txtPrecio;
    private javax.swing.JTextField txtSubtotal;
    private javax.swing.JTextField txtSubtotalD;
    private javax.swing.JTextField txtTelefono;
    private javax.swing.JTextField txtTotal;
    // End of variables declaration//GEN-END:variables
}
